package com.sinosoft.tcmneim.util;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @author 尹豪
 * @date 2021/9/10 14:45
 */
@Component
@Aspect
public class LogAspect {

    private Logger logger = LoggerFactory.getLogger(getClass());

    //定义切入点
    @Pointcut("execution(* com.sinosoft.tcmneim.controller..*.*(..))")
    public void logPointcut() {

    }

    //定义一个环绕通知
    @org.aspectj.lang.annotation.Around("logPointcut()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable{
        logger.info("=====================================Method  start====================================");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        long start = System.currentTimeMillis();

        try {
            Object result = joinPoint.proceed();
            long end = System.currentTimeMillis();
            logger.info("请求地址:" + request.getRequestURI());
            logger.info("用户IP:" + request.getRemoteAddr());
            logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
            logger.info("参数: " + Arrays.toString(joinPoint.getArgs()));
            logger.info("执行时间: " + (end - start) + " ms!");
            logger.info("=====================================Method  End====================================");
            return result;
        } catch (Throwable e){
            long end = System.currentTimeMillis();
            logger.info("URL:" + request.getRequestURI());
            logger.info("IP:" + request.getRemoteAddr());
            logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
            logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));
            logger.info("执行时间: " + (end - start) + " ms!");
            logger.info("=====================================Method  End====================================");
            throw e;
        }
    }
}
